Telegram Group & Telegram Channel
Анти-функциональные опции в Go

Часто в Go можно встретить такую конструкцию:


type Options struct {
Timeout time.Duration
Retries int
Logger *log.Logger
}

func DoSomething(ctx context.Context, opts Options) error {
if opts.Timeout == 0 {
opts.Timeout = 5 * time.Second
}
if opts.Retries == 0 {
opts.Retries = 3
}
if opts.Logger == nil {
opts.Logger = log.Default()
}

// дальше используем opts
}


На первый взгляд — удобно. Но на практике это ведёт к скрытым багам и неочевидному поведению. Почему?

🔸 Проблема 1: нулевое значение может быть валидным

Допустим, я хочу отключить ретраи и передаю Retries: 0. Но функция решает, что "ноль — это дефолт", и перезаписывает его на 3. В итоге получается поведение, которого явно не хотел.

🔸 Проблема 2: смешение ответственности

Функция DoSomething теперь делает больше, чем нужно: она и бизнес-логику выполняет, и значения инициализирует. Это противоречит принципу единственной ответственности и усложняет тестирование.

🔸 Проблема 3: дублирование

Если в коде много таких функций, каждая будет по-своему инициализировать Options. Это ведёт к дублированию и рассыпанной логике дефолтов.


💡 Что делать?

Вынеси дефолтные значения в отдельную функцию:


func DefaultOptions() Options {
return Options{
Timeout: 5 * time.Second,
Retries: 3,
Logger: log.Default(),
}
}


Теперь клиентский код выглядит явно:


opts := DefaultOptions()
opts.Retries = 0 // без ретраев

DoSomething(ctx, opts)


https://rednafi.com/go/dysfunctional_options_pattern/

👉 @golang_lib



tg-me.com/golang_lib/492
Create:
Last Update:

Анти-функциональные опции в Go

Часто в Go можно встретить такую конструкцию:


type Options struct {
Timeout time.Duration
Retries int
Logger *log.Logger
}

func DoSomething(ctx context.Context, opts Options) error {
if opts.Timeout == 0 {
opts.Timeout = 5 * time.Second
}
if opts.Retries == 0 {
opts.Retries = 3
}
if opts.Logger == nil {
opts.Logger = log.Default()
}

// дальше используем opts
}


На первый взгляд — удобно. Но на практике это ведёт к скрытым багам и неочевидному поведению. Почему?

🔸 Проблема 1: нулевое значение может быть валидным

Допустим, я хочу отключить ретраи и передаю Retries: 0. Но функция решает, что "ноль — это дефолт", и перезаписывает его на 3. В итоге получается поведение, которого явно не хотел.

🔸 Проблема 2: смешение ответственности

Функция DoSomething теперь делает больше, чем нужно: она и бизнес-логику выполняет, и значения инициализирует. Это противоречит принципу единственной ответственности и усложняет тестирование.

🔸 Проблема 3: дублирование

Если в коде много таких функций, каждая будет по-своему инициализировать Options. Это ведёт к дублированию и рассыпанной логике дефолтов.


💡 Что делать?

Вынеси дефолтные значения в отдельную функцию:


func DefaultOptions() Options {
return Options{
Timeout: 5 * time.Second,
Retries: 3,
Logger: log.Default(),
}
}


Теперь клиентский код выглядит явно:


opts := DefaultOptions()
opts.Retries = 0 // без ретраев

DoSomething(ctx, opts)


https://rednafi.com/go/dysfunctional_options_pattern/

👉 @golang_lib

BY Библиотека Go (Golang) разработчика




Share with your friend now:
tg-me.com/golang_lib/492

View MORE
Open in Telegram


Библиотека Go Golang разработчика Telegram | DID YOU KNOW?

Date: |

Telegram auto-delete message, expiring invites, and more

elegram is updating its messaging app with options for auto-deleting messages, expiring invite links, and new unlimited groups, the company shared in a blog post. Much like Signal, Telegram received a burst of new users in the confusion over WhatsApp’s privacy policy and now the company is adopting features that were already part of its competitors’ apps, features which offer more security and privacy. Auto-deleting messages were already possible in Telegram’s encrypted Secret Chats, but this new update for iOS and Android adds the option to make messages disappear in any kind of chat. Auto-delete can be enabled inside of chats, and set to delete either 24 hours or seven days after messages are sent. Auto-delete won’t remove every message though; if a message was sent before the feature was turned on, it’ll stick around. Telegram’s competitors have had similar features: WhatsApp introduced a feature in 2020 and Signal has had disappearing messages since at least 2016.

Should I buy bitcoin?

“To the extent it is used I fear it’s often for illicit finance. It’s an extremely inefficient way of conducting transactions, and the amount of energy that’s consumed in processing those transactions is staggering,” the former Fed chairwoman said. Yellen’s comments have been cited as a reason for bitcoin’s recent losses. However, Yellen’s assessment of bitcoin as a inefficient medium of exchange is an important point and one that has already been raised in the past by bitcoin bulls. Using a volatile asset in exchange for goods and services makes little sense if the asset can tumble 10% in a day, or surge 80% over the course of a two months as bitcoin has done in 2021, critics argue. To put a finer point on it, over the past 12 months bitcoin has registered 8 corrections, defined as a decline from a recent peak of at least 10% but not more than 20%, and two bear markets, which are defined as falls of 20% or more, according to Dow Jones Market Data.

Библиотека Go Golang разработчика from cn


Telegram Библиотека Go (Golang) разработчика
FROM USA